package com.design.cfr.model;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Chain responsibility result
 *
 * @description: 责任连执行结果
 * @author: cyj
 * @date 2022 -08-12 18:10:02
 */
@Data
public final class ChainResponsibilityResult {

    /**
     * Apply pass 只要有一个责任链上的节点失败，就是失败
     */
    private boolean applyPass;

    /**
     * Apply result elements 责任链节点结果
     */
    private List<ChainResponsibilityElementResult> applyResultElements = new LinkedList<>();

    /**
     * 设置结果
     */
    public void setResult() {
        applyPass = applyResultElements.stream().filter(applyResultElement -> !applyResultElement.isPass()).count() == 0;
    }

    /**
     * 检查执行结果
     */
    public void check() {
        if (!applyPass) {
            List<String> message = applyResultElements.stream()
                    .filter(chainResponsibilityElementResult -> !chainResponsibilityElementResult.isPass())
                    .map(chainResponsibilityElementResult -> String.format("%s:%s", chainResponsibilityElementResult.getAClass(),
                            chainResponsibilityElementResult.getMessage()))
                    .collect(Collectors.toList());
            throw new RuntimeException(StringUtils.join(message));
        }
    }

}
